package com.fansl.allround.common.core.exception;

import com.fansl.allround.common.core.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author fansl
 * @Description: 全局异常处理
 * @date 2019/6/24 18:56
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 全局异常捕获
     * @param e
     * @return
     */
    @ExceptionHandler({Exception.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R exception(Exception e){
        log.error("全局异常信息 ex={}",e.getMessage(),e);
        return new R<>(e);
    }

    /**
     * 参数校验异常捕获
     * @param exception
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class,BindException.class,AllroundBizException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R bodyValidExceptionHandler(Exception exception){
        R result = new R();
        if (exception instanceof MethodArgumentNotValidException){
            List<FieldError> fieldErrors = ((MethodArgumentNotValidException) exception)
                            .getBindingResult().getFieldErrors();
            result.setMsg(fieldErrors.get(0).getDefaultMessage());
        }else if (exception instanceof BindException){
            List<FieldError> fieldErrors = ((BindException) exception)
                    .getBindingResult().getFieldErrors();
            result.setMsg(fieldErrors.get(0).getDefaultMessage());
        }else{
            result.setMsg(exception.getMessage());
        }
        log.warn("参数校验异常：{}",result.getMsg());
        return result;
    }
}
